//
//  SYWebViewController.swift
//  股票框架
//
//  Created by 李小骥 on 2017/10/13.
//  Copyright © 2017年 李小骥. All rights reserved.
//


//网页交互逻辑有问题，有待更新！！！！！！



import UIKit
import WebKit

class DKSWebViewController: UIViewController,UIWebViewDelegate,NSURLConnectionDelegate,WKWebViewDelegate {
    
    let wkWebView = WebView()
    
     init(selfType:JumpFrom){
        self.selfType = selfType
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    var basicUrl:String{
        return updateUrl(basicUrl:selfType.returnUrlString())
    }
    var currentUrl = ""
    var loadUrl = ""{
        willSet{
//            refreshUrl(url: newValue)
        }
    }//只要 loadUrl 变化时就需要重新马上 get 一下 basicurl 并且载入
    var uuid = ""//初始化时使用判断 LCode 是否有值（uuid）来赋值，没有的话就是“”，然后 willSet 方法中根据 newvalue 是新 uuid 还是“”，重新调用页面刷新的方法
    func updateUrl(basicUrl:String)->String{
        if(basicUrl.hasPrefix("http")){
            if (lCode != nil && lCode?.userID != ""){
                let uuid = lCode!.userID
                return basicUrl+"/uuid/\(uuid)"
            }else{
                return basicUrl+"/uuid/-1"
            }
            return basicUrl
        }else{//实际上是.my 的原生资料界面，安全起见返回首页网址
            return JumpFrom.home.returnUrlString()
        }
    }
    //检查拦截的网址，返回是否允许通行，内部可能调用很多其它函数
    func checkUrl(urlString:String)->(Bool,String){//后续改成使用 uuid新值 来做判定，可以写进 uuid 的 willset 里面
        //包含register时的2种情况：有 uuid 应该转换网址，true，否则跳到登录 false
//        没有 register 直接放行，true
//basicUrl改成了 currentUrl
//        原来逻辑
//        if(urlString == basicUrl){
//            return (true , "basicUrl")
//        }
        if(urlString == basicUrl || urlString == currentUrl){
            return (true , "through")
        }
        if (urlString.contains("register")){
            //如果没有 lCode 的 uuid 是空的，则应该去原生界面，如果 lCode 有 uuid 则应该转换网址
            if (lCode == nil){
                return (false,"NativeLogin")
            }else{
                return (true,convertToAccessableUrl(registerUrl: urlString))
            }
        }else{
            return (true,urlString)
        }
//                let lgvc = loginViewController()
//                lgvc.registerUrl = url
//                lgvc.jumpFrom = selfType
//                self.navigationController?.pushViewController(lgvc, animated: true)
//                return false
//            }else{
//                loadUrl = convertToAccessableUrl(registerUrl: url)
//                jumpToNewPage(loadUrl: loadUrl)
//                return true
//            }
//        }
    }
//    var pageCount:Int = 0
//    {
//        willSet{
//            print(newValue)
//            if(newValue == 0){
//                backItem.customView?.isHidden = true
//                print(backItem.customView?.isHidden)
//                closeItem.customView?.isHidden = true
//                print(closeItem.customView?.isHidden)
//            }else{
//                backItem.customView?.isHidden = false
//                print(backItem.customView?.isHidden)
//                closeItem.customView?.isHidden = false
//                print(closeItem.customView?.isHidden)
//            }
//        }
//    }
    var selfType:JumpFrom
//    var webView = WebView()
//    var request:URLRequest?
    var isAuthed = false
//    lazy var backItem:UIBarButtonItem = {
//            let bki = UIBarButtonItem()
////        let bki = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(backNative))
//            let btn = UIButton(type: .custom)
////            let image = UIImage(named: "左侧返回")
////            btn.setImage(image, for: .normal)
//            btn.tintColor = .white
////            navigationController?.navigationBar.backIndicatorImage = UIImage(named: "左侧返回")
////            navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "左侧返回")
//            btn.setTitle(" < 返回", for: .normal)
//            btn.addTarget(self, action: #selector(backNative), for: .touchUpInside)
//            btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
//            btn.setTitleColor(.white, for: .normal)
//            btn.sizeToFit()
//            btn.contentHorizontalAlignment = .left
//            btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0)
//            btn.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
//            bki.customView = btn
//        return bki
//    }()
//    lazy var closeItem:UIBarButtonItem = {
//
//        let cli = UIBarButtonItem()
//        let btn = UIButton(type: .custom)
//        btn.tintColor = .white
//        btn.setTitle("关闭", for: .normal)
//        btn.addTarget(self, action: #selector(closeNative), for: .touchUpInside)
//        btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
//        btn.setTitleColor(.white, for: .normal)
//        btn.sizeToFit()
//        btn.contentHorizontalAlignment = .left
////        btn.frame = CGRect(x: 20, y: 0, width: 40, height: 40)
//        cli.customView = btn
//        return cli
//    }()
    var theBool = false
    var progressView = UIProgressView()
    var timer = Timer()
    //声明一个方法，外接调用时，只需要传递一个URL即可

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
//        webView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height - 64)
//        view.addSubview(webView)
////        self.addLeftButton()
//        self.addProgressBar()
//        webView.delegate = self
        print("+++++++++++++++++++\(currentUrl)-----------")
        if(currentUrl == ""){
            loadUrl = basicUrl
        }else{
            loadUrl = currentUrl
        }
        self.automaticallyAdjustsScrollViewInsets = false
        
        
        //测试 1030
        
        var config = WkwebViewConfig()
        config.isShowScrollIndicator = false
        config.isProgressHidden = false
        wkWebView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height - 64)
        view.addSubview(wkWebView)
        // 加载普通URL ""中字符串为前后台商议的标识
        config.scriptMessageHandlerArray = ["submitFromWeb"]
        wkWebView.webConfig = config
        wkWebView.delegate = self
        
        if (lCode != nil && lCode?.userID != ""){
            let uuid = lCode!.userID
            wkWebView.webloadType(self, .URLString(url: basicUrl+"/uuid/\(uuid)"))
            
        }else{
            wkWebView.webloadType(self, .URLString(url: basicUrl+"/uuid/-1"))

        }

    }
        
//        updateUrl()
//        loadHTML(htmlString: loadUrl)
        // Do any additional setup after loading the view.
//    }

//    func loadHTML(htmlString:String){
//        let url = URL(string: htmlString)
//        request = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 5.0)
//        webView.loadRequest(request!)
//    }
//    func addLeftButton(){
//        navigationItem.leftBarButtonItem = backItem
//    }
//    func refreshUrl(url:String) {
//        if(webView.isLoading){
//            webView.stopLoading()
//        }
//        loadHTML(htmlString: url)
//    }
    func convertToAccessableUrl(registerUrl:String) -> String{
        //        var url = (newUrl == "") ? basicUrl : newUrl
        //        var url = "http://xy.cctvzxjy.com/Index/index/s/1"
        //        取到最后的部分，然后替换浪线为/，最后把
        //        原地址：http://xy.cctvzxjy.com/Register/register/url/Bunch~watch~id~74
        //        转换结果：http://xy.cctvzxjy.com/Bunch/watch/id/74/uuid/1467
        //        算法：http://xy.cctvzxjy.com/+（原地址最后一个/后面的内容，把~替换成/）+uuid/1467
        let lastPart = registerUrl.components(separatedBy: "/").last
//        var filtered = url.stringByReplacingOccurrencesOfString("?", withString: "/", options: NSStringCompareOptions.LiteralSearch, range: nil)
        print("#########\(lastPart)########")
//        转换回来的字符串实际上是 Unicode 编码，此处的~是%7E，建议之后把所有可能出现的Unicode 编码都修改出来
        let convertedPart = lastPart!.replacingOccurrences(of: "%7E", with: "/")
                print("$$$$$$$$$\(convertedPart)$$$$$$$$$$")
        let host = "http://xy.cctvzxjy.com/"    //"/uuid/\(uuid)")
         let uuidPart = "/uuid/\(lCode!.userID)"
//        let uuidPart = "/uuid/\(lCode!.userID)"
        let newUrl = host + convertedPart + uuidPart
        print("^^^^^^^^^^^^^\(newUrl)^^^^^^^^^^")
        return newUrl
    }
    func addProgressBar(){
        let progressBarHeight:CGFloat = 0.5
        let navigationBarBounds:CGRect = navigationController!.navigationBar.bounds
        let barFrame:CGRect = CGRect(x:0, y:navigationBarBounds.size.height - progressBarHeight, width:navigationBarBounds.size.width, height:progressBarHeight)
        progressView = UIProgressView(frame: barFrame)
//        progressView.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleTopMargin.rawValue)))
        progressView.autoresizingMask = UIViewAutoresizing(rawValue: (UIViewAutoresizing.flexibleWidth.rawValue | UIViewAutoresizing.flexibleTopMargin.rawValue))
        //        UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin
        progressView.trackTintColor = .gray
        progressView.progressTintColor = .blue
        navigationController?.navigationBar.addSubview(progressView)
    }
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let scheme = request.url?.scheme
        if(scheme == "https"){
            if(isAuthed == false){
                let conn = NSURLConnection(request: request, delegate: self)
                conn?.start()
                webView.stopLoading()
                return false
            }
        }
        let url = (request.url?.absoluteString)!
//
        let (allowContinue,newUrl) = checkUrl(urlString: url)
        if (allowContinue == false){
            let lgvc = LoginViewController()
            lgvc.registerUrl = url
            lgvc.jumpFrom = selfType
            self.navigationController?.pushViewController(lgvc, animated: true)
            return false
        }else{
            if(newUrl == "through"){
//                loadHTML(htmlString: basicUrl)
                return true
            }else{
                jumpToNewPage(loadUrl: newUrl)
                return false
            }
        }
//        return allowContinue
        }

    @objc func jumpToNewPage(loadUrl:String){
        let naviBarTitleAttributes = NSDictionary(object: UIColor.white, forKey: NSAttributedStringKey.foregroundColor as NSCopying)
        let newWebViewController = DKSWebViewController(selfType: selfType)//SearchStockViewController()
//        searchStockViewController.marketViewControllerDelegate = self
        newWebViewController.currentUrl = loadUrl
        newWebViewController.navigationItem.title = ""
        let newWebViewNavigationController = UINavigationController(rootViewController: newWebViewController)
        newWebViewNavigationController.navigationBar.setBackgroundColor(.APP)
        newWebViewNavigationController.navigationBar.titleTextAttributes = (naviBarTitleAttributes as! [NSAttributedStringKey : Any])
        //        防止重复弹出
        let viewController = UIApplication.shared.keyWindow?.rootViewController
        if let isNavigationController = viewController?.presentedViewController?.isKind(of: UINavigationController.self){
            if(isNavigationController == true){
                let navigation = viewController?.presentedViewController as! UINavigationController
                if(navigation.topViewController?.isKind(of: SearchStockViewController.self))!{
                    return
                }
            }
        }
        if((viewController?.presentedViewController) != nil){
//            viewController?.presentedViewController?.dismiss(animated: false, completion: {
                //下方有可能改这句
//                /*viewController?.*/self.present(stockDetailViewNavigationController, animated: true, completion: nil)
            self.present(newWebViewNavigationController, animated: true, completion: nil)
//                viewController?.present(newWebViewNavigationController, animated: true, completion: nil)
//            })
        }else{
            viewController?.present(newWebViewNavigationController, animated: true, completion: nil)
        }
        
//
//        //        这是原先避免重复跳转的写法，暂时改成直接跳转试试
//        if((viewController?.presentedViewController) != nil){
//            viewController?.presentedViewController?.dismiss(animated: false, completion: {
//                //                以下的 self 暂时不知道怎么改成 weakself
//                /*viewController?.*/self.present(stockDetailViewNavigationController, animated: true, completion: nil)
//            })
//        }else{
//            viewController?.present(stockDetailViewNavigationController, animated: true, completion: nil)
//        }

        
        //        navigationController?.pushViewController(searchStockViewController, animated: true)
        //        present(searchStockViewNavigationController, animated: true, completion: nil)
    }
    /// 页面加载完成
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        theBool = true
        navigationItem.title = webView.title
//            webView.stringByEvaluatingJavaScript(from: "document.title")
    }
//    func webViewDidFinishLoad(_ webView: UIWebView) {
//        theBool = true
//        navigationItem.title = webView.stringByEvaluatingJavaScript(from: "document.title")
//    }
    func connection(_ connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: URLProtectionSpace) -> Bool {
        return (protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust)
    }
    func connection(_ connection: NSURLConnection, willSendRequestFor challenge: URLAuthenticationChallenge) {
        if(challenge.previousFailureCount == 0){
            isAuthed = true
            let cre = URLCredential(trust: challenge.protectionSpace.serverTrust!)
            challenge.sender?.use(cre, for: challenge)
        }
    }
//    func connection(_ connection: NSURLConnection, didFailWithError error: Error) {
//        print("网络不好")
//    }
//    func connection(_ connection: NSURLConnection, didReceive response: URLResponse){
//        isAuthed = true
//        webView.loadRequest(request!)
//        connection.cancel()
//    }

//    @objc func backNative(){
//        if(wkWebView.canGoBack){
//            wkWebView.goBack()
////            navigationItem.leftBarButtonItems = [backItem,closeItem]
//        }else{
//            closeNative()
//        }
//    }
    @objc func closeNative(){
        navigationController?.popViewController(animated: true)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        progressView .removeFromSuperview()
    }
    override func viewWillAppear(_ animated: Bool) {
        navigationController?.navigationBar.setBackgroundColor(.APP)
        if(currentUrl == ""){
            navigationItem.setHidesBackButton(true, animated: true)
        }else{
            navigationItem.setHidesBackButton(false, animated: true)
        }
        makeReturnButton()
    }
    func makeReturnButton(){
        let bki = UIBarButtonItem()
        let btn = UIButton(type: .custom)
        btn.tintColor = .white
        btn.setTitle(" < ", for: .normal)
        btn.addTarget(self, action: #selector(backNative), for: .touchUpInside)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        btn.setTitleColor(.white, for: .normal)
        btn.sizeToFit()
        btn.contentHorizontalAlignment = .left
        btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0)
        btn.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        bki.customView = btn
        navigationItem.leftBarButtonItem = bki
    }
    @objc func backNative(){
//        if(wkWebView.canGoBack()){
//            wkWebView.goBack()
////            navigationItem.leftBarButtonItems = [backItem,closeItem]
//        }else{
//            closeNative()
//        }

        navigationController?.dismiss(animated: true, completion: nil)
    }
    
    /// 页面开始加载
     func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
        progressView.progress = 0
        theBool = false
        timer = Timer.scheduledTimer(timeInterval: 0.01667, target: self, selector: #selector(timerCallback), userInfo: nil, repeats: true)
    }
    
    func webViewUserContentController(_ scriptMessageHandlerArray: [String], didReceive message: WKScriptMessage) {
            print(message.body)
    }
    
//    func webViewDidStartLoad(_ webView: UIWebView) {
//        progressView.progress = 0
//        theBool = false
//        timer = Timer.scheduledTimer(timeInterval: 0.01667, target: self, selector: #selector(timerCallback), userInfo: nil, repeats: true)
//    }
    @objc func timerCallback(){
        if(theBool == true){
            if(progressView.progress >= 1){
                progressView.isHidden = true
                timer.invalidate()
            }else{
                progressView.progress += 0.1
            }
        }else{
            progressView.progress += 0.1
            if(progressView.progress >= 0.9){
                progressView.progress = 0.9
            }
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

//extension ViewController:WKWebViewDelegate{
//
//    func webViewUserContentController(_ scriptMessageHandlerArray: [String], didReceive message: WKScriptMessage) {
//        print(message.body)
//    }
//
//}

